<?php
require_once 'DB/db_data_loader.php';
$measures = get_support_measures();
$array = "";
foreach ($measures['CODE'] as $key => $value) {
    if ($array != "")
	$array .= ", ";
    //$array .= '"' . $measures['TITLE'][$key] . '" : "' . $value . '"';
    $array .= '"' . $value . '"';
}
//$array = "{" . $array . "}";
$array = "[" . $array . "]";

$dates = "";
$date = strtotime(date("Y-m")."-01");
$endDate = strtotime("2006-01-01");
while($date > $endDate) {
    if ($dates != "")
	$dates .= ", ";
    $dates .= '"' . date("Y-m-d", $date) . '"';
    $date = strtotime(date("Y-m-d", $date)." - 1 month");
}
$dates = "[".$dates."]";
?>

<?php
$processed = array();
if (isset($_POST['direct'])) {
    $direct = $_POST['direct'];
    foreach ($direct['measure'] as $key => $value) {
	if ($direct['measure'][$key] != "" && $direct['period'][$key] != "" && $direct['administrated'][$key] != "") {
	    $date = strtotime($direct['period'][$key]);
	    if(in_array($value, $measures['CODE']) && preg_match('/^[0-9]+$/', $direct['administrated'][$key]) && $date != "" && checkdate(date("n", $date), date("j", $date), date("Y", $date)) && preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $direct['period'][$key])) {
		$date2 = date("Y-m", $date)."-01";
		$sql = "INSERT INTO historical_quantities (measure_code, date, administrated) VALUES ('{$value}', '$date2', {$direct['administrated'][$key]}) ON DUPLICATE KEY UPDATE administrated = administrated + {$direct['administrated'][$key]}";
		mysql_query($sql);
                require_once 'GUI/Diagrams/diagrams_processing.php';
                Diagrams::clear_cache();
		$processed[] = array("status" => "done", "measure" => $direct['measure'][$key], "period" =>$direct['period'][$key],"administrated" =>$direct['administrated'][$key]);
	    } else {
		$processed[] = array("status" => "failed", "measure" => $direct['measure'][$key], "period" =>$direct['period'][$key],"administrated" =>$direct['administrated'][$key]);
	    }
	} else {
	    $processed[] = array("status" => "skiped", "measure" => $direct['measure'][$key], "period" =>$direct['period'][$key],"administrated" =>$direct['administrated'][$key]);
	}
    }
    array_pop($processed);
}
?>

<style type="text/css">
    table#direct_import { width: 100%; }
    table#direct_import thead td { width:22%; align:left;}
    table#direct_import input { width:100px; }
    table#direct_import td.nr { width:5%;}
    ol li.done {color:green;}
    ol li.failed {color:red;}
    ol li.skiped {color:orange;}
    ol #done {color:green;}
    ol #failed {color:red;}
    ol #skiped {color:orange;}
    ul.ui-autocomplete {width:60px; list-style-type: none; padding-left: 10px; font-size:0.8em}
</style>
<script type="text/javascript" src="Plugins/Misc/autocomplete.js"></script>
<script type="text/javascript">
    //init values
    var measures = <?php print $array; ?>;
    for (key in measures) {
	//alert(measures[key]);
    }
    var dates = <?php print $dates; ?>;
    var lastRow = 0;
</script>
<script type="text/javascript">
    function addEvent() {
	$("table#direct_import input").focus(function() {
	    selectedRow = $($(this).parent("td")).parent("tr").attr("id");
	    if(selectedRow == lastRow) {
		if($("table#direct_import tr#"+lastRow.toString()+" input.measure").val() != "" || $("table#direct_import tr#"+lastRow.toString()+" input.period").val() != "") {
		    lastRow++;
		    addRow();
		    addEvent();
		}
	    }
	});
	$(".measure").autocomplete({source:measures, delay:0});
	$(".period").autocomplete({source:dates, delay:0});
	$(".measure").keyup(function() {
	    var found = false;
	    for (key in measures) {
		if(measures[key].indexOf($(this).val()) == 0) {
		    found = true;
		}
	    }
	    if(!found) {
		$(this).addClass("badInput");
                show_near(this, "Nerastas padalinio kodas", 'error');
	    } else {
		$(this).removeClass("badInput");
                hide_near();
	    }
	});
    }
    function addRow() {
	row = "";
	row += '<tr id="'+lastRow+'">';
	row += '<td class="nr">'+ (lastRow+1) +'.</td>';
	row += '<td><input type="text" class="measure" name="direct[measure]['+lastRow+']" autocomplete="off" title="Egzistuojančios paramos priemonės kodas. Mažosios ir didžiosios raidės skiriasi"/></td>';
	row += '<td><input type="text" class="period" name="direct[period]['+lastRow+']" autocomplete="off" title="Paraiškų apdorojimo laikotarpis, formatas: YYYY-MM-DD, pvz: 2000-12-01"/></td>';
	row += '<td><input type="text" class="administrated" name="direct[administrated]['+lastRow+']" value="0" autocomplete="off" title="Suadministruotų paraiškų kiekis, sveikas skaičius"/></td>';
	row += "</tr>";
	$("table#direct_import").append(row);

	nmDate(".period");
	nmDecimal(".administrated");
    }
</script>

<?php
    //print_r($processed);
    if(isset($_POST['direct']) && count($processed) > 0) {
	print "<ol>";
	foreach($processed as $data) {
	    print "<li class='{$data['status']}'>";
	    if($data['measure'] == "" || !in_array($data['measure'], $measures['CODE'])) {
		print "<u><b>Paramos priemonė</b>: ".$data['measure']." </u>";
	    } else {
		print "<b>Paramos priemonė</b>: ".$data['measure']." ";
	    }

	    //print "<b>Paramos priemonė</b>: ".$data['period']." ";
	    if($data['period'] == "" || !preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $data['period']) || $date == "" || !checkdate(date("n", $date), date("j", $date), date("Y", $date))) {
		print "<u><b>Data</b>: ".$data['period']." </u>";
	    } else {
		print "<b>Data</b>: ".$data['period']." ";
	    }

	    //print "<b>Suadministruota</b>: ".$data['administrated'];
	    if($data['administrated'] == "" || !preg_match('/^[0-9]+$/', $data['administrated'])) {
		print "<u><b>Suadministruota</b>: ".$data['administrated']." </u>";
	    } else {
		print "<b>Suadministruota</b>: ".$data['administrated']." ";
	    }

	    print "</li>";
	}
	print "<br/>";
	print "<label id='done'>Įrašyta.</label> ";
	print "<label id='skiped'><u>Praleistas duomuo.</u></label> ";
	print "<label id='failed'><u>Padaryta klaida.</u></label>";
	print "</ol>";
    }
?>
<form name="direct" method="post" action="index.php?input">
    <table id="direct_import" class="new_application_table">
	<thead><td class="nr">Nr.</td><td>Paramos priemonė</td><td>Laikotarpis</td><td>Suadministruota</td></thead>
    </table>
    <input type="submit" value="Išsaugoti"/>
</form>

<script type="text/javascript">
    //init events
    addRow();
    addEvent();
</script>